// pages/music/index.js
const ac =  wx.getBackgroundAudioManager()
let lastIndex 
Page({
	pause(e){ 
		console.log(this.data.paused?'播放play':'暂停pause')
		let paused=!this.data.paused
		if(paused)ac.pause()
		else ac.play()
		this.setData({paused})
	},
	play(e) {
		let index=e.currentTarget.dataset.index
		let change={paused:false} 
		if(lastIndex!=null){
			if(index==lastIndex)return
			change[`songs[${lastIndex}].selected`]=false 
		}
		change[`songs[${index}].selected`]=true 
		lastIndex=index 
		this.setData(change) 
		let id=this.data.songs[index].id 
		let mp3 = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
		console.log('playing...',mp3)
        ac.src = mp3 
        ac.title=this.data.songs[index].name
       // ac.startTime=180
		ac.play() 
	},
	formatDuration(ms) { 
		ms = parseInt(ms / 1000) 
		let minute = parseInt(ms / 60) 
		ms %= 60 
		return minute + ":" + (ms < 10 ? '0' : '') + ms 
  },
  onUnload(){ 
    let songMessage=this.data 
    delete songMessage.__webviewId__ 
    delete songMessage.inputKey
    wx.setStorageSync('songMessage', songMessage) 
},
    onLoad(options) { 
      let songMessage=wx.getStorageSync('songMessage') 
      console.log(songMessage, typeof songMessage) 
      if(songMessage){
          this.setData(songMessage) 
      }
        ac.onEnded(()=>{ 
            let index=lastIndex+1
            if(index==this.data.songs.length)index=0 
            this.play({currentTarget:{dataset:{index}}}) 
        })
		this.search({detail:{value:'蒋大为'}}) 
    },
    search(e){ 
        let search=e.detail.value.trim()
        if(!search)return 
        this.setData({search, inputKey:'', songs:[]})
        this.request(search) 
	},
	onReachBottom(){ 
		console.log('onReachBottom~')
		this.request(this.data.search)
  },
    request(key){ 
      let offset=this.data.songs.length 
      if(offset>=this.data.songCount)return 
        wx.request({
          url: `https://music.163.com/api/search/get/?s=${key}&limit=20&type=1&offset=${offset}`,
			complete: r => { 
				console.log(r) 
				if (r.errMsg == "request:ok" && r.data.result.songs) {
          let change={songCount: r.data.result.songCount} 
					r.data.result.songs.forEach(item => { 
						change[`songs[${offset++}]`]={
							id: item.id, 
							name: item.name, 
							duration: this.formatDuration(item.duration), 
							album: item.album.name,
						}
					})
					this.setData(change)
				}
			}
		})
    }
})